package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.adapter.MineGoodsAdapter;
import com.sdruixinggroup.mondayb2b.adapter.MineShopsAdapter;
import com.sdruixinggroup.mondayb2b.adapter.QuickAdapter;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.Collect;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.ui.WebActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import okhttp3.Call;

/**
 * Created by 00029935 on 2017/11/17.
 */

public class MineCollectFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.v_goods)
    View vGoods;
    @BindView(R.id.rl_goods)
    RelativeLayout rlGoods;
    @BindView(R.id.v_shops)
    View vShops;
    @BindView(R.id.rl_shops)
    RelativeLayout rlShops;
    @BindView(R.id.recyclerView)
    LFRecyclerView recyclerView;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.tv_goods)
    TextView tvGoods;
    @BindView(R.id.tv_shops)
    TextView tvShops;

    private MineGoodsAdapter goodsAdapter;
    private List<Collect.CollectBean.DataBean.GoodsBean> goodses;
    private MineShopsAdapter shopsAdapter;
    private List<Collect.CollectBean.DataBean.MerchantBean>  shopses;
    private int type = 1; //1 是商品 2 是 店铺
    private int page = 1;
    @Override
    protected int getInflateLayout() {
        return R.layout.mine_collect_activity;
    }

    @Override
    protected void setUpView(View view) {
        ibBack.setImageResource(R.mipmap.share_back);
        tvTitle.setText("我的收藏");

        goodsAdapter = new MineGoodsAdapter(getContext());
        goodses = new ArrayList<>();
        goodsAdapter.setData(goodses);
        goodsAdapter.setOnCancleCollectListener(new MineGoodsAdapter.OnCancleCollectListener(){
            @Override
            public void listener(Collect.CollectBean.DataBean.GoodsBean itemData, int position) {
                cancleCollect(itemData.getGoods_id(),position);
            }
        });
        goodsAdapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Collect.CollectBean.DataBean.GoodsBean>(){
            @Override
            public void OnItemClick(Collect.CollectBean.DataBean.GoodsBean data, int postion) {
                String params = "productdetail"+"?goods_id="+data.getGoods_id()+"&area_id="+ UserInfoUtil.AREA_CODE +"&latitude="+UserInfoUtil.mLatitude
                        +"&longitude="+UserInfoUtil.mLongitude;
                toWebView(params);
            }
        });

        shopsAdapter = new MineShopsAdapter(getContext());
        shopses = new ArrayList<>();
        shopsAdapter.setData(shopses);
        shopsAdapter.setOnCancleCollectListener(new MineShopsAdapter.OnCancleCollectListener(){
            @Override
            public void listener(Collect.CollectBean.DataBean.MerchantBean itemData, int position) {
                cancleCollect(itemData.getMerchant_id(),position);
            }
        });
        shopsAdapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Collect.CollectBean.DataBean.MerchantBean>(){
            @Override
            public void OnItemClick(Collect.CollectBean.DataBean.MerchantBean bean, int postion) {
                String params = "shopinfo?merchant_id="+bean.getMerchant_id()+"&area_id="+ UserInfoUtil.AREA_CODE +"&latitude="+UserInfoUtil.mLatitude
                        +"&longitude="+UserInfoUtil.mLongitude;
                toWebView(params);
            }
        });
        recyclerView.setRefresh(true);
        recyclerView.setLoadMore(true);
        recyclerView.setNoDateShow();
        recyclerView.setLFRecyclerViewListener(new LFRecyclerView.LFRecyclerViewListener(){
            @Override
            public void onRefresh() {
                queryData(true);
            }

            @Override
            public void onLoadMore() {
                queryData(false);
            }
        });

        setSelect(true);
        queryData(true);
    }


    private void setSelect(Boolean isGoods){
        if(isGoods){
            tvGoods.setSelected(true);
            tvShops .setSelected(false);
            vGoods.setVisibility(View.VISIBLE);
            vShops.setVisibility(View.GONE);
            recyclerView.setAdapter(goodsAdapter);
            type = 1;
        }else {
            tvGoods.setSelected(false);
            tvShops .setSelected(true);

            vGoods.setVisibility(View.GONE);
            vShops.setVisibility(View.VISIBLE);
            recyclerView.setAdapter(shopsAdapter);
            type = 2;
        }

        queryData(true);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.ib_back, R.id.rl_goods, R.id.rl_shops})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                getActivity().finish();
                break;
            case R.id.rl_goods:
                setSelect(true);
                break;
            case R.id.rl_shops:
                setSelect(false);
                break;
        }
    }

    private void queryData(final Boolean isReflush){

        if(isFirstIn ){
            isFirstIn = false;
            progress.setVisibility(View.VISIBLE);
        }

        if(isReflush){
            page = 1;
        }
        String url = API.COLLECTS+type+"&page="+page+"&page_size=10"+"&access_token="+ UserInfoUtil.getInfoToken(getContext());
        Log.e("1234","url="+url);
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<Collect> typeToken = new TypeToken<Collect>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<Collect>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if(null != progress){
                    progress.setVisibility(View.GONE);
                }

                if(null != recyclerView){
                    recyclerView.stopLoadMore();
                    recyclerView.stopRefresh(true);
                }
            }

            @Override
            public void onResponse(Collect response, int id) {
                if(isReflush){
                    goodses.clear();
                    shopses.clear();
                }

                if (null != response) {
                    if (response.getErr_code() == 0) {

                        List<Collect.CollectBean.DataBean> dataBeen = response.getCollect().getData();
                            ++page;
                        if (type == 1) {

                            for (Collect.CollectBean.DataBean bean : dataBeen) {
                                Collect.CollectBean.DataBean.GoodsBean goodsBean = bean.getGoods();
                                goodses.add(goodsBean);
                            }
                            goodsAdapter.reflashData(goodses);
                        } else if (type == 2) {
                            for (Collect.CollectBean.DataBean bean : dataBeen) {
                               Collect.CollectBean.DataBean.MerchantBean merchant = bean.getMerchant();
                                shopses.add(merchant);
                            }
                            shopsAdapter.reflashData(shopses);
                        }
                    } else {
                        showMsgToast(response.getErr_msg());
                    }
                }

                if(null != progress){
                    progress.setVisibility(View.GONE);
                }

                if(null != recyclerView){
                    recyclerView.stopLoadMore();
                    recyclerView.stopRefresh(true);
                }
            }
        });
    }

    private void cancleCollect(int id,final int position){
        String url = "";
        if(type == 1){
         url = API.GOODS_COLLECT+id+"/collect/remove?access_token="+UserInfoUtil.getInfoToken(getContext());
        }else if(type == 2){
            url = API.MERCHANTS_COLLECT+id+"/collect/remove?access_token="+UserInfoUtil.getInfoToken(getContext());
        }

        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };
        OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                        if(response.err_code == 0){
                            if(type == 1){
                                goodses.remove(position);
                                goodsAdapter.reflashData(goodses);
                            }else if(type == 2){
                                shopses.remove(position);
                                shopsAdapter.reflashData(shopses);
                            }
                        }else{
                            showMsgToast(response.err_msg);
                        }
            }
        });
    }


    private void toWebView(String param) {
        Intent intent = new Intent(getContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);
        startActivity(intent);
    }
}
